package com.bradz.mytv;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
 
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
 
import android.util.Log;
 
//Simple json parsing
public class classJSONParser {
 
    public JSONObject getJSONfromURL(String url){

    	//initialize
    	InputStream is = null;
    	String result = "";
    	JSONObject jArray = null;

    	//http post
    	try{
    		HttpClient httpClient = new DefaultHttpClient();
    		
    		HttpGet request = new HttpGet(url);

            HttpResponse response = httpClient.execute(request);
            HttpEntity entity = response.getEntity();
            StatusLine statusLine = response.getStatusLine();
    		
    		Log.i("myTV - JSONParser", "Status: " + statusLine.toString());
    		is = entity.getContent();
    		Log.i("myTV - JSONParser", "Content: " + is.toString());

    	}catch(Exception e){
    		Log.e("log_tag", "Error in http connection "+e.toString());
    	}

    	//convert response to string
    	try{
    		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    		StringBuilder sb = new StringBuilder();
    		String line = null;
    		while ((line = reader.readLine()) != null) {
    			Log.i("myTV - JSONParser", "Line: " + line);
    			sb.append(line + "\n");
    		}
    		is.close();
    		result=sb.toString();
    	}catch(Exception e){
    		Log.e("log_tag", "Error converting result "+e.toString());
    	}

    	//try parse the string to a JSON object
    	try{
            	jArray = new JSONObject(result);
    	}catch(JSONException e){
    		Log.e("log_tag", "Error parsing data "+e.toString());
    	}

    	return jArray;
    } 
}